package com.dl.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dl.common.enums.StatusTypeEnum;
import com.dl.common.utils.SecurityUtils;
import lombok.extern.java.Log;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectionException;

import java.util.Date;

/**
 * 字段自动填充工具，在mybatis-plus执行新增和更新操作的时候，会对指定字段进行自动填充分隔符，例如：create_time等字段
 */
@Log
public class CustomMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            this.setValue("createBy", this.getUsername(), metaObject);
            this.setValue("createTime", new Date(), metaObject);
            this.setValue("statusFlag", StatusTypeEnum.STATUS_FLAG_NORMAL.getCode(), metaObject);
        } catch (ReflectionException e) {
            log.warning("CustomMetaObjectHandler处理过程中无相关字段，不做处理");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            this.setValue("updateBy", this.getUsername(), metaObject);
            this.setValue("updateTime", new Date(), metaObject);
        } catch (ReflectionException e) {
            log.warning("CustomMetaObjectHandler处理过程中无相关字段，不做处理");
        }
    }

    /**
     * 设置属性
     */
    private void setValue(String fieldName, Object fieldVal, MetaObject metaObject) {
//        Object originalAttr = getFieldValByName(fieldName, metaObject);
//        if (ObjectUtil.isEmpty(originalAttr)) {
            setFieldValByName(fieldName, fieldVal, metaObject);
//        }
    }

    /**
     * 获取用户名
     */
    private String getUsername() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            log.warning("CustomMetaObjectHandler处理过程中获取用户账户异常，不做处理");
            return null;
        }
    }
}
